<template>
	<view class="container">
	</view>
</template>

<script>
	const jsApi = require('jweixin-module')
	export default {
		data() {
			return {
				orderModel: null,
				code: null,
			}
		},
		computed: {
			weixin() {
				return this.isWeixin()
			}
		},
		onLoad() {
			console.log(this.$Route.query);
			
			//苹果手机H5支付跳转不同浏览器时拦截请求
			if(! this.$store.state.isLogin ){
				uni.showModal({
					title: '支付完成提示',
					content: '请返回您下单时使用的浏览器查看支付结果',
					showCancel: false
				})
				return
			}
			//苹果手机H5支付跳转不同浏览器时拦截请求
			
			//获取本地订单数据
			console.log(this.$Route.query.orderModel);
			if(this.$Route.query.orderModel){
				uni.setStorageSync('orderModel', JSON.stringify(this.$Route.query.orderModel))
				this.orderModel = this.$Route.query.orderModel
			}else{
				let orderModel = uni.getStorageSync('orderModel')
				if(orderModel){
					this.orderModel = JSON.parse(orderModel)
				}
			}
			//获取本地订单数据
			
			//根据本地订单数据下单支付
			if(!this.orderModel){
				console.log('参数错误');
				uni.showModal({
					title: '错误提示',
					content: '数据请求错误，请返回重试',
					showCancel: false,
					success: () => {
						this.$Router.replace({name: 'userrecharge'})
					}
				})
			}else{
				//判断浏览器
				if(!this.weixin){
					//非微信下进行下单支付流程
					this.createOrder()
				}else{
					//拦截微信code
					if(this.$Route.query.code){
						this.code = this.$Route.query.code
						this.pageUrl = window.location.href.split('#')[0]
						console.log(this.pageUrl);
						//微信下使用JSAPI
						this.jsApiOrder()
					}else{
						//跳转打开code链接
						let redirect_url = window.location.href + '?wxcode=1' //获取code后的回跳地址，固定配置，勿动
						let url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid="+this.$CHS.config.wxAppId+"&redirect_uri="+ encodeURIComponent(redirect_url) + "&response_type=code&scope=snsapi_base&state=wxpay#wechat_redirect" //固定配置，勿动
						window.location.href = url
						//跳转打开code链接
					}
				}
			}
			//根据本地订单数据下单支付
		},
		methods: {
			//检查是否已有订单
			checkHaveOrder() {
				//formdata支付完成后通过返回URL参数获取，或者从本地存储获取
				let formdata = uni.getStorageSync('formdata')
				if(formdata){
					let out_trade_no = JSON.parse(formdata).out_trade_no
					this.checkOrderStatus(out_trade_no)
				}else{
					uni.showModal({
						title: '错误提示',
						content: '没有找到您的订单信息，请稍后重试',
						showCancel: false,
					})
				}
			},
			//微信下支付完成检测
			checkOrderStatus(orderNum) {
				this.$http.get({
					url: '/api/userRechargeRecord/verifyPayResult',
					data: {
						orderNum
					}
				}).then(data => {
					console.log(data)
					if(data.success && data.code == 200 && data.result){
						console.log('验证通过后进入成功页面');
						uni.showToast({
							title: data.message,
							icon: 'success',
							duration: 1000
						})
						this.$ShowToast({text: data.message})
						this.$store.dispatch('updateUserinfo')
						setTimeout(()=>{
							this.$CHS.rechargeSuccess(true)
						}, 1000);
						return
					}
					uni.showToast({
						title: '订单未支付！',
						icon: 'error'
					})
				}).catch((err) => {
					console.log(err);
				})
			},
			//非微信浏览器H5统一下单支付
			createOrder() {
				//具体流程根据后端返回数据确定
				this.$http.post({
					url: '/api/userRechargeRecord/createOrder',
					data: {
						...this.orderModel
					}
				}).then(data => {
					console.log(data);
					if(data.success && data.result){
						//保存formdata，用于校验订单是否支付
						let formdata = {
							out_trade_no: data.result.orderNum
						}
						uni.setStorageSync('formdata', JSON.stringify(formdata))
						
						//保存下单记录
						uni.setStorageSync('haveOrder', true)
						//跳转打开微信支付链接
						let url = data.result.wxPayMwebOrderResult.mwebUrl
						let redirect_url = window.location.href + '?wxback=1' //自定义支付完成后的跳转URL
						window.location.href = url + '&redirect_url='+ encodeURIComponent(redirect_url)
						//跳转打开微信支付链接
					}else{
						console.log(data.message)
						this.payError('订单创建失败，请返回充值页面重试')
					}
				}).catch((err) => {
					console.log(err)
					this.payError('订单创建失败，请返回充值页面重试')
				})
			},
			//微信浏览器JSAPI统一下单支付
			jsApiOrder() {
				this.$http.post({
					url: '/api/userRechargeRecord/createOrder',
					data: {
						code: this.code,
						...this.orderModel
					},
				}).then(data => {
					console.log(data);
					if(data.success && data.result){
						//保存formdata，用于校验订单是否支付
						let formdata = {
							out_trade_no: data.result.orderNum
						}
						uni.setStorageSync('formdata', JSON.stringify(formdata))
						
						//打开微信支付
						this.weixinJsApiPay(data.result.wxPayMpOrderResult)
						
						/* jsApi.config({
							debug: false, // 是否开启调试模式
							appId: data.result.wxPayMpOrderResult.appId, //必填
							//nonceStr: data.result.wxPayMpOrderResult.nonceStr, // 必填，生成签名的随机串
							//signature: data.result.signature, // 必填，签名
							//timestamp: String(data.result.wxPayMpOrderResult.timeStamp), //必填，字符串格式时间戳
							jsApiList: ['chooseWXPay'] // 必填，需要使用的JS接口列表
						});
						jsApi.ready(()=> {
							//保存下单记录
							uni.setStorageSync('haveOrder', true)

							jsApi.chooseWXPay({
								appId: data.result.wxPayMpOrderResult.appId,
								nonceStr: data.result.wxPayMpOrderResult.nonceStr,
								package: data.result.wxPayMpOrderResult.packageValue,
								paySign: data.result.wxPayMpOrderResult.paySign,
								signType: data.result.wxPayMpOrderResult.signType,
								timestamp: String(data.result.wxPayMpOrderResult.timeStamp),
								success: (res) => {
									// 支付成功后的回调函数
									this.paySuccess()
								},
								cancel: (res) => {
									console.log(res)
									this.payError('已取消支付，继续充值请返回充值页面')
								},
								fail: (err) => {
									console.log(err)
									if(err && err.errMsg){
										this.payError('微信支付失败，失败原因：'+err.errMsg)
									}else{
										this.payError('微信支付失败，请返回重试')
									}
								}
							});
						});
						jsApi.error((err) => {
							console.log(err)
							if(err && err.errMsg){
								this.payError('微信支付失败，失败原因：'+err.errMsg)
							}else{
								this.payError('微信支付失败，请返回充值页面重试')
							}
						}); */
					}else{
						console.log(data.message)
						this.payError(data.message || '订单创建失败，请返回充值页面重试')
					}
				}).catch((err) => {
					console.log(err)
					this.payError('订单创建失败，请返回充值页面重试')
				})
			},
			//微信内置浏览器JSAPI支付
			weixinJsApiPay(wxPayMpOrderResult) {
				let that = this
				function onBridgeReady() {
					//保存下单记录
					uni.setStorageSync('haveOrder', true)
					//调起支付
					WeixinJSBridge.invoke(
						'getBrandWCPayRequest',
						{
							"appId": wxPayMpOrderResult.appId, //公众号ID，由商户传入
							"nonceStr": wxPayMpOrderResult.nonceStr, //随机串     
							"package": wxPayMpOrderResult.packageValue, 
							"paySign": wxPayMpOrderResult.paySign,//微信签名 
							"signType": wxPayMpOrderResult.signType, //微信签名方式
							"timeStamp": wxPayMpOrderResult.timeStamp, //时间戳，自1970年以来的秒数     
						},
						(res) => {
							console.log(res);
							if(res.err_msg == "get_brand_wcpay_request:ok"){
								// 支付成功后的回调
								that.paySuccess()
							}else if(res.err_msg == "get_brand_wcpay_request:cancel"){
								that.payError('已取消支付，继续充值请返回充值页面')
							}else{
								that.payError('微信支付失败，请返回重试')
							}
						}
					); 
				}
				//检测WeixinJSBridgeReady状态
				if (typeof WeixinJSBridge == "object" && typeof WeixinJSBridge.invoke == "function") {
					onBridgeReady();
				} else {
					if( document.addEventListener ){
						document.addEventListener('WeixinJSBridgeReady', onBridgeReady, false);
					}else if (document.attachEvent){
						document.attachEvent('WeixinJSBridgeReady', onBridgeReady); 
						document.attachEvent('onWeixinJSBridgeReady', onBridgeReady);
					}
				}
			},
			//支付失败
			payError(content) {
				//清理本地缓存数据
				uni.removeStorageSync('haveOrder')
				uni.removeStorageSync('orderModel')
				uni.removeStorageSync('formdata')
				//提示返回充值页面
				uni.showModal({
					title: '支付提示',
					content: content,
					showCancel: false,
					success: (res) => {
						if(res.confirm){
							this.$Router.replace({name: 'userrecharge'})
						}
					}
				})
			},
			//支付成功
			paySuccess() {
				//成功提示
				uni.showToast({
					title: '充值成功！',
					icon: 'success',
					duration: 1000
				})
				this.$ShowToast({text: '充值成功！'})
				//更新用户数据
				this.$store.dispatch('updateUserinfo')
				//清理本地缓存数据
				uni.removeStorageSync('orderModel')
				uni.removeStorageSync('haveOrder')
				//uni.removeStorageSync('formdata')
				//成功后页面跳转
				setTimeout(()=>{
					this.$Router.replace({name: 'userrecharge', params: {success: 1}})
				}, 1000);
			},
			//判断浏览器类型
			isWeixin() {
				let ua = navigator.userAgent.toLowerCase();
				if (ua.match(/micromessenger/i) == "micromessenger"){
					console.log(1);
					return true
				}else{
					console.log(2);
					return false
				}
			}
		}
	}
</script>

<style lang="scss" >

</style>